package com.mrroman.linksender.twitter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.logging.Logger;

import com.mrroman.linksender.Configuration;
import com.mrroman.linksender.ioc.In;
import com.mrroman.linksender.ioc.Log;
import com.mrroman.linksender.ioc.Name;
import com.mrroman.linksender.sender.Message;
import com.mrroman.linksender.sender.MessageEvent;
import com.mrroman.linksender.sender.MessageListener;
import com.mrroman.linksender.sender.MessageEvent.EventType;

@Name("twitter.TwitterMessageListener")
public class TwitterMessageListener implements MessageListener {

	@In
	private Configuration configuration;
	
	@Log
	private Logger logger;
	
	@Override
	public void messageSend(MessageEvent event) {
		
		// check if you ought to send messages to Twitter
		
		if (!configuration.isSendToTwitter())
			return;
		
		// send only event messages
		
		if (event.getEvent() != EventType.MESSAGE) 
			return;
		
		Message message = event.getMessage();
		
		if (((message.getFlags() & Message.MESSAGE_FLAG_HIDDEN) > 0) &&
				((message.getFlags() & Message.MESSAGE_FLAG_PRIVATE) > 0))
			return;

		if (!message.getMessage().contains("http://") && !message.getMessage().contains("https://"))
			return;
	
		new Thread(new TwitterSender(message)).start();
	}

	@Override
	public void serverInfo(MessageEvent event) {
		
	}
	
	private class TwitterSender implements Runnable {
		
		private Message message;
		
		public TwitterSender(Message message) {
			this.message = message;
		}

		@Override
		public void run() {
			try {
				URLConnection conn = new URL(
						"https://twitter.com/statuses/update.xml").openConnection();

				conn.setDoOutput(true);

				PrintWriter out = new PrintWriter(new OutputStreamWriter(conn
						.getOutputStream()));
				out.print("status=" + URLEncoder.encode(
						message.getMessage(),
						"UTF-8"));
				out.flush();
				out.close();

				BufferedReader in = new BufferedReader(new InputStreamReader(conn
						.getInputStream()));

				while (in.readLine() != null)
					;
				
				in.close();
			} catch (IOException ex) {
				logger.severe("Cannot send message to Twitter: " + ex.getMessage());
			}
		}
		
	}

}
